import java.util.*;


public class Solution787 {
    class Element{
        int tmpLoc;
        int stepAccount;
        int amount;

        public Element(int tmpLoc, int stepAccount, int amount) {
            this.tmpLoc = tmpLoc;
            this.stepAccount = stepAccount;
            this.amount = amount;
        }
    }
    int[][] matrix;
    int[] res;

    public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) {
        res = new int[n];
        Arrays.fill(res, Integer.MAX_VALUE);
        res[src] = 0;
        matrix = new int[n][n];
        for (int[] flight:flights) {
            matrix[flight[0]][flight[1]] = flight[2];
        }
        Queue<Element> q = new LinkedList<>();
        q.offer(new Element(src, 0, 0));
        while (!q.isEmpty()){
            Element tmpEle = q.poll();
            if(tmpEle.stepAccount > k+1){
                continue;
            }
            if(tmpEle.amount > res[tmpEle.tmpLoc]){
                continue;
            }
            res[tmpEle.tmpLoc] = tmpEle.amount;
            int[] tmpNeighbours = matrix[tmpEle.tmpLoc];
            for (int i = 0; i < n; i++) {
                int neighbourAmount =tmpNeighbours[i];
                if(neighbourAmount == 0){
                    continue;
                }
                q.offer(new Element(i, tmpEle.stepAccount+1, tmpEle.amount+neighbourAmount));
            }
        }
        return res[dst] == Integer.MAX_VALUE? -1:res[dst];
    }

    public static void main(String[] args) {
        Solution787 s = new Solution787();
        System.out.println(s.findCheapestPrice(3,
               new int[][] {{0,1,100},{1,2,100},{0,2,500}},
        0,
        2,
        1));
    }
}
